<template>
  <div class="chart-warp">
    <button class="btn-back">返回</button>
    <div class="road-line">
      <span v-for="(item,i) in parentInfo" :key="i">
        {{ item.cityName }}
        <template v-if="i!==(parentInfo.length-1)">></template>
      </span>
    </div>
    <div ref="mapChart" class="chartDv" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'MapChart',
  data() {
    return {
      parentInfo: [{
        cityName: '全国',
        code: 100000
      }],
      currentIndex: 0,
      timeTitle: ['2015', '2016', '2017', '2018', '2019'],
      geoJson: []
    }
  },
  mounted() {
    const _this = this
    const myChart = echarts.init(document.querySelector('.chartDv'))
    const parentInfo = [{
      cityName: '全国',
      code: 100000
    }]
    const currentIndex = 0
    const timeTitle = ['2015', '2016', '2017', '2018', '2019']
    init('china')
    function init(adcode) {
      getGeoJson(adcode).then(data => {
        getMapData(data)
      })
    }
    function getGeoJson(adcode) {
      return new Promise((resolve, reject) => {
        const url = '/static/json/' + adcode + '.json'
        _this.$http.get(url).then(({ body }) => {
          resolve(body)
        }).catch((error) => {
          reject(error)
        })
      })
    }
    function getMapData(geoJson) {
      let mapData = []
      const pointData = []
      let sum = 0
      geoJson.features.forEach(item => {
        const value = Math.random() * 3000
        if (!item.properties.center) {
          return
        }
        mapData.push({
          name: item.properties.name,
          value: value,
          cityCode: item.properties.adcode
        })
        pointData.push({
          name: item.properties.name,
          value: [item.properties.center[0], item.properties.center[1], value],
          cityCode: item.properties.adcode
        })
        sum += value
      })
      mapData = mapData.sort(function(a, b) {
        return b.value - a.value
      })

      initEchartMap(mapData, sum, pointData, geoJson)
    }
    function initEchartMap(mapData, sum, pointData, geoJson) {
      const xData = []
      const yData = []
      let min = mapData[mapData.length - 1].value
      const max = mapData[0].value
      if (mapData.length === 1) {
        min = 0
      }
      mapData.forEach(c => {
        xData.unshift(c.name)
        yData.unshift(c.value)
      })
      // 这里做个切换，全国的时候才显示南海诸岛  只有当注册的名字为china的时候才会显示南海诸岛
      echarts.registerMap(parentInfo.length === 1 ? 'china' : 'map', { geoJSON: geoJson })
      const option = {
        backgroundColor: '#012248',
        title: [
          {
            left: 'center',
            top: 10,
            text: parentInfo[parentInfo.length - 1].cityName + '销售额统计图(可点击下钻到县)',
            textStyle: {
              color: 'rgb(179, 239, 255)',
              fontSize: 16
            }
          },
          {
            text: '销售总额：' + sum.toFixed(2) + '万',
            left: 'center',
            top: '6.5%',
            textStyle: {
              color: '#FFAC50',
              fontSize: 26
            }
          }
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          right: '2%',
          top: '12%',
          bottom: '8%'
        },
        toolbox: {
          feature: {
            restore: {
              show: false
            },
            dataView: {
              show: false
            },
            saveAsImage: {
              name: parentInfo[parentInfo.length - 1].cityName + '销售额统计图'
            },
            dataZoom: {
              show: false
            },
            magicType: {
              show: false
            }
          },
          iconStyle: {
            borderColor: '#1990DA'
          },
          top: 15,
          right: 35
        },
        geo: {
          map: parentInfo.length === 1 ? 'china' : 'map',
          zoom: 1.1,
          roam: true,
          left: 'center',
          top: 'center',
          tooltip: {
            trigger: 'item',
            formatter: (p) => {
              let val = p.value[2]
              if (window.isNaN(val)) {
                val = 0
              }
              const txtCon =
                            "<div style='text-align:left'>" + p.name + ':<br />销售额：' + val.toFixed(2) + '万</div>'
              return txtCon
            }
          },
          label: {
            show: true,
            color: 'rgb(249, 249, 249)', // 省份标签字体颜色
            formatter: p => {
              switch (p.name) {
                case '内蒙古自治区':
                  p.name = '内蒙古'
                  break
                case '西藏自治区':
                  p.name = '西藏'
                  break
                case '新疆维吾尔自治区':
                  p.name = '新疆'
                  break
                case '宁夏回族自治区':
                  p.name = '宁夏'
                  break
                case '广西壮族自治区':
                  p.name = '广西'
                  break
                case '香港特别行政区':
                  p.name = '香港'
                  break
                case '澳门特别行政区':
                  p.name = '澳门'
                  break
              }
              return p.name
            }
          },
          emphasis: {
            itemStyle: {
              areaColor: '#8dd7fc',
              borderWidth: 1.6,
              shadowBlur: 25
            },
            label: {
              show: true,
              color: '#f75a00'
            }
          },
          itemStyle: {
            areaColor: '#24CFF4',
            borderColor: '#53D9FF',
            borderWidth: 1.3,
            shadowBlur: 15,
            shadowColor: 'rgb(58,115,192)',
            shadowOffsetX: 7,
            shadowOffsetY: 6
          },
          regions: [
            {
              name: '南海诸岛',
              itemStyle: {
                opacity: 0
              },
              label: {
                show: false
              },
              tooltip: {
                show: false
              },
              emphasis: {
                itemStyle: {
                  opacity: 0
                },
                label: {
                  show: false
                }
              }
            }
          ]
        },
        visualMap: {
          min: min,
          max: max,
          left: '3%',
          bottom: '5%',
          calculable: true,
          seriesIndex: [0],
          inRange: {
            color: ['#24CFF4', '#2E98CA', '#1E62AC']
          },
          textStyle: {
            color: '#24CFF4'
          }
        },
        series: [{
          name: timeTitle[currentIndex] + '年销售额度',
          type: 'map',
          geoIndex: 0,
          map: parentInfo.length === 1 ? 'china' : 'map',
          roam: true,
          zoom: 1.3,
          tooltip: {
            trigger: 'item',
            formatter: p => {
              let val = p.value
              if (p.name === '南海诸岛') return ''
              if (window.isNaN(val)) {
                val = 0
              }
              const txtCon =
                            "<div style='text-align:left'>" + p.name + '<br />销售额：' + val.toFixed(2) + '万</div>'
              return txtCon
            }
          },
          label: {
            show: false
          },
          data: mapData

        }]
      }
      myChart.setOption(option, true)
      myChart.off('click')
      myChart.on('click', echartsMapClick)
    }
    function echartsMapClick(params) {
      if (parentInfo.length === 3) {
        return
      }
      if (!params.data) {
        return
      } else {
        // 如果当前是最后一级，那就直接return
        if (parentInfo[parentInfo.length - 1].code === params.data.cityCode) {
          return
        }
        const data = params.data
        const city = ['北京市', '上海市', '重庆市', '天津市', '香港', '澳门']
        if (city.indexOf(parentInfo[parentInfo.length - 1].cityName) !== -1 && parentInfo.length === 2) {
          return
        }
        parentInfo.push({
          cityName: data.name,
          code: data.cityCode
        })
        _this.parentInfo = parentInfo
        init(data.cityCode)
      }
    }
    document.querySelector('.btn-back').addEventListener('click', () => {
      if (parentInfo.length === 1) {
        return
      }
      parentInfo.pop()
      _this.parentInfo = parentInfo
      let code = parentInfo[parentInfo.length - 1].code
      if (code === 100000) {
        code = 'china'
      }
      init(code)
    })
  }
}
</script>

<style scoped lang="less">
    .chartDv{
        width: 100%;
        height: 640px;
    }
    .btn-back{
        position: fixed;
        left: 40px;
        top: 40px;
        z-index: 999;
    }
    .road-line{
        position: fixed;
        top: 80px;
        left: 40px;
        z-index: 999;
        color: #f2f2f2;
        font-size: 12px;
    }
</style>
